# encoding:utf-8
import requests
import json
import base64
import os

# client_id 为官网获取的AK， client_secret 为官网获取的SK
AK = 'beiPfGktq5zyG7TqVweGkwvz'
SK = 'G9BVjUW6yfYUYpUfQ86UffegrB9vURtg'
null = ''


def get_token():
    url = 'https://aip.baidubce.com/oauth/2.0/token'
    data = {}
    data['grant_type'] = 'client_credentials'
    data['client_id'] = AK
    data['client_secret'] = SK
    response = requests.post(url, data)
    content = response.content.decode('utf-8')
    content = json.loads(content)
    print('access_token:\t', content['access_token'])
    return content['access_token']


def base666(image):
    f1 = open(image, 'rb')
    f1_64 = base64.b64encode(f1.read())
    f1.close()
    f1_64 = f1_64.decode()
    return f1_64


def tansfer(face1,face2, image):
    global null
    url = 'https://aip.baidubce.com/rest/2.0/face/v1/transfer' + \
          "?access_token=" + get_token()
    data = {
        "source_image": {"image": base666(face1), "image_type": "BASE64", },
        "reference_images": [
            {"image": base666(face2), "image_type": "BASE64", }
        ]
    }
    data = json.dumps(data)
    headers = {'content-type': 'application/json'}
    response = requests.post(url, data, headers=headers)
    # print(response.content)
    req_con1 = response.content.decode('utf-8')
    content = eval(req_con1)
    print(content)
    result1 = content['result']
    result = result1['transfer_image']
    imgdata = base64.b64decode(result)
    with open(image, 'wb') as fp:
        fp.write(imgdata)
        fp.close()

if __name__ == '__main__':
    image2 = './nomakeup1.jpg'
    image1 = './makeup0.jpg'
    image = './makeup01.jpg'
    tansfer(image1,image2, image)